package com.etime.shycourse.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.etime.shy.common.BaseMessage;
import com.etime.shycourse.services.account.interfaces.OnlineCourseAccountService;
import com.etime.shycourse.dao.*;
import com.etime.shycourse.orde.dao.OrdersMapper;
import com.etime.shycourse.orde.pojo.Orders;
import com.etime.shycourse.pojo.*;
import com.etime.shycourse.services.interfaces.NotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 小程序支付反馈消息业务逻辑层实现类
 */
@Service
public class NotifyServiceImpl implements NotifyService {
    @Autowired
    private NotifyDao notifyDao;
    @Autowired
    private Notify2Dao notify2Dao;
    @Autowired
    private OrdersMapper ordersMapper;
//    @Autowired
//    private AccountDao accountDao;
    @Autowired
    private CouponlogMapper couponlogMapper;
    @Autowired
    private CouponreciveMapper couponreciveMapper;
    @Autowired
    private OnlineCourseAccountService onlineCourseAccountService;
    /**
     * 支付成功后，修改状态
     * @param notifyxml
     * @param resultMap
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String wxnotify(String notifyxml, Map<String,String> resultMap) {
         /*1、记录支付日志（支付返回的原始数据）
          2、记录支付日志，拆分字段。
          3、支付流水
          4、修改订单状态为“已完成”
          5、如果有优惠券，修改优惠券的使用记录和使用状态
          6、结算提成
        */
         //1 记录支付日志（支付返回的原始数据）
        try {
            Notify notify = new Notify();
            notify.setPost(notifyxml);
            notify.setCreatedtime(new Date());
            int rtn = notifyDao.insert(notify);
            //2 记录支付日志明细
            int rtn2 = savenotify2(resultMap);
            //4 修改订单状态
            int rtn3 = updateOrders(resultMap, notifyxml);
            //5修改优惠券使用记录
            updateCoupon(resultMap);
            // 6结算提成
            Orders orders = selectOrderByNo(resultMap.get("out_trade_no"));
            onlineCourseAccountService.onlineCourseAccount(orders);
        }catch (Exception e){
            e.printStackTrace();
            throw  e;
            //return "0";
        }
        return "1";
    }

    /**
     * 修改优惠券使用情况
     * @param resultMap
     * @return
     */
    private int updateCoupon(Map<String,String> resultMap){
        Orders orders = selectOrderByNo(resultMap.get("out_trade_no"));
        if(orders!=null && orders.getOrdercouponreciveid()!=null){
            Integer reciveid=orders.getOrdercouponreciveid();
            Couponrecive couponrecive = couponreciveMapper.selectById(reciveid);
            couponrecive.setCouponrecivestate(2);
            couponrecive.setCouponrecivestatetime(new Date());
            couponreciveMapper.updateById(couponrecive);
            //记录优惠券日志
            Couponlog log = new Couponlog();
            log.setCouponid(couponrecive.getCouponid());
            log.setCouponlongreciveid(couponrecive.getCouponreciveid());
            log.setCouponno(couponrecive.getCouponno());
            log.setCouponloguserid(couponrecive.getCouponreciveuserid());
            log.setCouponlogusername(couponrecive.getCouponreciveusername());
            log.setCouponlogtype(2);
            log.setCouponlogtime(new Date());
            log.setCouponlogdesc("使用优惠券");
            couponlogMapper.insert(log);
        }
        return 1;
    }
    /**
     * 支付成功后查询订单状态信息
     *
     * @param orderno
     * @return
     */
    @Override
    public Orders selectOrderByNo(String orderno) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("orderno",orderno);
        Orders orders = ordersMapper.selectOne(wrapper);
        return orders;
    }

    /**
     * 0元支付订单
     *业务逻辑：
     * 1）修改订单状态=2；支付金额=0
     * 2）修改订单使用的优惠券状态，修改为已使用；
     * 3）添加优惠券的使用日志
     * @param orderid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseMessage payzero(Integer orderid) {
        BaseMessage msg = new BaseMessage();
        //查询出订单详情
        Orders orders = ordersMapper.selectById(orderid);
        //查询出订单所使用的优惠券信息
        Couponrecive couponrecive = couponreciveMapper.selectById(orders.getOrdercouponreciveid());
        try{
            //修改订单信息
            orders.setOrderstate(2);
            orders.setOrderpaycash(new BigDecimal(0));
            orders.setOrderpaytime(new Date());
            orders.setOrderpayment("抵扣券");
            orders.setOrderupdatetime(new Date());
            ordersMapper.updateById(orders);
            //处理优惠券使用情况
            if(couponrecive != null){
                couponrecive.setCouponrecivestate(2);
                couponrecive.setCouponrecivestatetime(new Date());
                couponreciveMapper.updateById(couponrecive);
                //记录优惠券日志
                Couponlog log = new Couponlog();
                log.setCouponid(couponrecive.getCouponid());
                log.setCouponlongreciveid(couponrecive.getCouponreciveid());
                log.setCouponno(couponrecive.getCouponno());
                log.setCouponloguserid(couponrecive.getCouponreciveuserid());
                log.setCouponlogusername(couponrecive.getCouponreciveusername());
                log.setCouponlogtype(2);
                log.setCouponlogtime(new Date());
                log.setCouponlogdesc("使用优惠券");
                couponlogMapper.insert(log);
            }
            msg.setCode(1);
            msg.setMsg("订单处理成功。");
        }catch (Exception e){
            e.printStackTrace();
            msg.setCode(0);
            msg.setMsg("订单处理失败，请联系管理员。");
            throw e;
        }
        return msg;
    }

//    /**
//     * 添加支付流水（待写）
//     * @param resultMap
//     * @return
//     */
//    private int insertAccount(Map<String,String> resultMap){
//        //1、根据订单号查询订单及订单明细，并且查出订单商品涉及的教师
//        //2、遍历查询结果，并存入到支付流水中；
//        Account account = new Account();
//        account.setAcctype(1);
//        account.setAcccurrencytype(1);
//        //订单id
//        account.setAccorderid(0);
//
//        return 0;
//    }

    /**
     * 修改订单状态
     * @param resultMap
     * @return
     */
    private int updateOrders(Map<String,String> resultMap,String notifyxml){
        Orders orders = new Orders();
        //orders.setOrderno(resultMap.get("out_trade_no"));
        orders.setOrderpricetype(1);
        orders.setOrderstate(2);
        orders.setOrdertradeno(resultMap.get("transaction_id"));
        double totalfee = Double.parseDouble(resultMap.get("total_fee")) / 100;
        orders.setOrderpaycash(BigDecimal.valueOf(totalfee));
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Date timeend = new Date();
        try {
            timeend = df.parse(resultMap.get("time_end"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //支付完成后，是未结算状态。计算提成完成后是已结算状态
        orders.setOrderaccountstate(0);
        orders.setOrderpaytime(timeend);
        orders.setOrderpayment("微信支付");
        orders.setOrdercallback(notifyxml);
        orders.setOrderupdatetime(new Date());
        UpdateWrapper<Orders> wrapper = new UpdateWrapper();
        wrapper.eq("orderno",resultMap.get("out_trade_no"));
        //orders.setOrderpaycash();
        return ordersMapper.update(orders,wrapper);
    }

    /**
     * 保存支付反馈记录
     * @param resultMap
     * @return
     */
    private int savenotify2(Map<String,String> resultMap){
        Notify2 notify2 = new Notify2();
        notify2.setAppid(resultMap.get("appid"));
        notify2.setBanktype(resultMap.get("bank_type"));
        notify2.setCashfee(Integer.parseInt(resultMap.get("cash_fee")));
        notify2.setFeetype(resultMap.get("fee_type"));
        notify2.setIssubscribe(resultMap.get("is_subscribe"));
        notify2.setMchid(resultMap.get("mch_id"));
        notify2.setNoncestr(resultMap.get("nonce_str"));
        notify2.setOpenid(resultMap.get("openid"));
        notify2.setOuttradeno(resultMap.get("out_trade_no"));
        notify2.setResultcode(resultMap.get("result_code"));
        notify2.setReturncode(resultMap.get("return_code"));
        notify2.setSign(resultMap.get("sign"));
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Date timeend = new Date();
        try {
            timeend = df.parse(resultMap.get("time_end"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        notify2.setTimeend(timeend);
        notify2.setTotalfee(Integer.parseInt(resultMap.get("total_fee")));
        notify2.setTradetype(resultMap.get("trade_type"));
        notify2.setTransactionid(resultMap.get("transaction_id"));
        return notify2Dao.insert(notify2);
    }
}
